﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Xiaov.SmartWeb.Model.ActiveRecord;
using Xiaov.SmartWeb.Infrastructure.ExtMethod;
using Xiaov.SmartWeb.Infrastructure.Common;
using System.Data;

namespace Xiaov.SmartWeb.Application.PluginSrc.StatisticalSystem.ReportDesign.Json
{
    public partial class ExportBBBMB : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            //单位编码
            string dwbm = Request["dwbm"].ToRequestString();

            DataTable dt = Maticsoft.DBUtility.DbHelperOra.Query(@"select x.bbbm,''||BBWH||'['||lbmc||']'||y.bbmc as bbmc ,y.bbbm as cb,'0' as parentid from code_bbbmb x,
(
select a.bbmc as bbmc,a.bbbm ,a.bblx from bbdytbdw t  left join code_bbbmb a on t.bbbm=a.bbbm where t.dwbm='"+dwbm+"') y,enco_bblx z where x.bbbm=y.bbbm and y.bblx=z.id order by z.id, x.bbbm asc").Tables[0];
            Response.Clear();
            Response.Write(ToJsonForTree_Sepcial(dt,"BBBM", "BBMC", "Parentid", "0"));
            
            Response.End();

        }

        private string ToJsonForTree_Sepcial(DataTable dt, string idField, string textField, string parentIdField, string rootIdValue)
        {
            string JsonData = "[";
            DataRow[] drs = dt.Select(parentIdField + "='" + rootIdValue + "'");
            foreach (var d in drs)
            {
                JsonData += "{";

                JsonData += "\"text\":\"" + d[textField].ToString() + "\",";
                JsonData += "\"id\":\"" + d[idField].ToString() + "\",";
                if (d["CB"].ToRequestString() != "")
                    JsonData += "\"checked\":true,";
                DataRow[] childdrs = dt.Select(parentIdField + "='" + d[idField] + "'");
                if (childdrs.Count() > 0)
                {
                    JsonData += "\"children\":";
                    JsonData += ToJsonForTree_Sepcial(dt, idField, textField, parentIdField, d[idField].ToString());
                    JsonData += "},";
                }
                else
                {
                    JsonData = JsonData.Remove(JsonData.Length - 1);
                    JsonData += "},";
                }
            }
            if (JsonData.Length > 1)
                JsonData = JsonData.Remove(JsonData.Length - 1);
            JsonData += "]";
            return JsonData;
        }
    }
}